<script setup lang="ts">
import {ref, reactive} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';

// 创建路由器实例
const router = useRouter();

// 定义表单数据
const form = reactive({
  email: '',
  password: ''
});

// 定义表单规则
const rules = {
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, message: '邮箱格式不正确', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不少于6位', trigger: 'blur'}
  ]
};

// 表单引用
const loginForm = ref(null);

// 提交表单
const submitForm = async (formName: string) => {
  // 校验表单
  if (!loginForm.value) return;
  loginForm.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 发送 POST 请求到登录 API
        const response = await axios.post('http://localhost:8088/api/auth/login', {
          username: form.email,
          password: form.password
        });

        // 如果登录成功，保存 token 并跳转到首页
        if (response.data.token) {
          localStorage.setItem('authToken', response.data.token);
          ElMessage.success('登录成功');
          router.push('/');
        } else {
          ElMessage.error('登录失败，请检查账号或密码');
        }
      } catch (error) {
        // 处理登录失败的情况
        ElMessage.error('登录失败，请检查账号或密码');
        console.error('Login failed:', error);
      }
    } else {
      ElMessage.error('请填写正确的信息');
      return false;
    }
  });
};
</script>

<template>
  <div class="login-container">
    <h2>登录</h2>
    <el-form :model="form" :rules="rules" ref="loginForm" label-width="80px" class="login-form">
      <!-- 邮箱输入框 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>

      <!-- 密码输入框 -->
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 300px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}
</style>